package cn.xunjie.ymcc.service.impl;

import cn.xunjie.ymcc.doc.CourseDoc;
import cn.xunjie.ymcc.domain.*;
import cn.xunjie.ymcc.dto.CourseDto;
import cn.xunjie.ymcc.feign.CourseSearchFeignClient;
import cn.xunjie.ymcc.feign.MediaSearchFeignClient;
import cn.xunjie.ymcc.feign.MessagesTationFeignClient;
import cn.xunjie.ymcc.mapper.CourseMapper;
import cn.xunjie.ymcc.mq.CourseProducer;
import cn.xunjie.ymcc.result.JSONResult;
import cn.xunjie.ymcc.service.*;
import cn.xunjie.ymcc.util.AssertUtil;
import cn.xunjie.ymcc.util.StrUtils;
import cn.xunjie.ymcc.vo.CourseDetilVo;
import cn.xunjie.ymcc.vo.CourseItemVo;
import cn.xunjie.ymcc.vo.CourserOrderVo;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.validation.Valid;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author xue.jiao
 * @since 2022-07-21
 */
@Service
public class CourseServiceImpl extends ServiceImpl<CourseMapper, Course> implements ICourseService {
    @Autowired
    private ITeacherService teacherService;
    @Autowired
    private ICourseDetailService courseDetailService;
    @Autowired
    private ICourseResourceService courseResourceService;
    @Autowired
    private ICourseMarketService courseMarketService;
    @Autowired
    private ICourseTeacherService courseTeacherService;
    @Autowired
    private ICourseTypeService courseTypeService;
    @Autowired
    private ICourseSummaryService courseSummaryService;
    @Autowired
    private CourseSearchFeignClient courseSearchFeignClient;
    @Autowired
    private MessagesTationFeignClient messagesTationFeignClient;
    @Autowired
    private CourseProducer courseProducer;
    @Autowired
    private ICourseChapterService courseChapterService;
    @Autowired
    private MediaSearchFeignClient mediaSearchFeignClient;


    @Override
    @Transactional
    public void save(CourseDto dto) {
        Course course = dto.getCourse();
        CourseDetail courseDetail = dto.getCourseDetail();
        CourseMarket courseMarket = dto.getCourseMarket();
        CourseResource courseResource = dto.getCourseResource();
        List<Long> teacharIds = dto.getTeacharIds();
        //空校验
        //课程不能被注册========================
        Course courseTmp = selectByName(course.getName());
        AssertUtil.isNull(courseTmp,"课程已经被注册");
        //* 保存数据===========================
        //* 保存课程
        // 做必要的参数的初始化  状态、讲师、  谁来添加的课程
        // 有些初始化的值，必须要在service层做填写，防止被黑客黑了
        course.setStatus(Course.STATE_OFFLINE);
        course.setLoginId(1L);
        course.setLoginUserName("yhptest1");
        List<Teacher> teachers = teacherService.selectBatchIds(teacharIds);
        StringBuilder sb = new StringBuilder();
        teachers.forEach(teacher -> {
            sb.append(teacher.getName()).append(",");
        });
        course.setTeacherNames(sb.toString());
        insert(course);
        //保存课程详情
        courseDetail.setId(course.getId());
        courseDetailService.insert(courseDetail);
        //保存课程销售
        courseMarket.setId(course.getId());
        courseMarketService.insert(courseMarket);
        //保存讲师
        teacharIds.forEach(id->{
            CourseTeacher courseTeacher = new CourseTeacher();
            courseTeacher.setCourseId(course.getId());
            courseTeacher.setTeacherId(id);
            courseTeacherService.insert(courseTeacher);
        });
        //保存课程资源
        courseResource.setCourseId(course.getId());
        courseResourceService.insert(courseResource);
        CourseSummary courseSummary = new CourseSummary();
        courseSummary.setId(course.getId());
        courseSummaryService.insert(courseSummary);
        CourseType type = courseTypeService.selectById(course.getCourseTypeId());
        type.setTotalCount(type.getTotalCount() + 1);
        courseTypeService.updateById(type);



    }

    @Override
    public void onLineCourse(Long courseId) {
        Course course = selectById(courseId);
        //判断是否为null
        AssertUtil.isNotNull(course,"课程不存在");
        //判断状态是否已经上架
       boolean off =  course.getStatus() == Course.STATE_OFFLINE;//0
       AssertUtil.isTrue(off,"课程状态不对");
       course.setStatus(Course.STATE_NOLINE);
       course.setOnlineTime(new Date());
       //修改
       updateById(course);
        CourseType type = courseTypeService.selectById(course.getCourseTypeId());
        CourseMarket courseMarket = courseMarketService.selectById(courseId);
        CourseSummary courseSummary = courseSummaryService.selectById(courseId);
        CourseDoc doc = new CourseDoc();
        BeanUtils.copyProperties(course,doc);
        BeanUtils.copyProperties(courseMarket,doc);
        BeanUtils.copyProperties(courseSummary,doc);
        doc.setCourseTypeName(type.getName());//这里要单独赋值
        String chargeName = courseMarket.getCharge() == 1 ? "免费" : "收费";
        doc.setChargeName(chargeName);
        JSONResult result = courseSearchFeignClient.saveCourse(doc);
        /*courseProducer.SendMessage(course);*/
        AssertUtil.isTrue(result.isSuccess(),"课程发布失败");



    }

    public JSONResult commonmessages(Course course) {
        JSONResult jsonResult = messagesTationFeignClient.saveAndUpdate(course);
        AssertUtil.isTrue(jsonResult.isSuccess(),"站内信推送失败");
        return JSONResult.success();
    }

    @Override
    public CourseDetilVo CourseDetail(Long courseId) {
        AssertUtil.isNotNull(courseId,"请求不合法id不能为空");
        CourseDetilVo vo = new CourseDetilVo();
        Course course = selectById(courseId);
        AssertUtil.isNotNull(course,"请求不合法");
        boolean b = course.getStatus() == Course.STATE_NOLINE;
        AssertUtil.isTrue(b,"你在搞事？");
        CourseDetail courseDetail = courseDetailService.selectById(courseId);
        CourseMarket courseMarket = courseMarketService.selectById(courseId);
        CourseSummary courseSummary = courseSummaryService.selectById(courseId);
        Wrapper<CourseTeacher> wrapper = new EntityWrapper<>();
        wrapper.eq("course_id",courseId);
        List<CourseTeacher> courseTeachers = courseTeacherService.selectList(wrapper);
        List<Long> techerIds = courseTeachers.stream().map(teacher -> teacher.getTeacherId()).collect(Collectors.toList());
        List<Teacher> teachers = teacherService.selectBatchIds(techerIds);
        Wrapper<CourseChapter> cwrapper = new EntityWrapper<>();
        cwrapper.eq("course_id",courseId);
        List<CourseChapter> courseChapters = courseChapterService.selectList(cwrapper);
        //性能低 直接传ids
        /*ArrayList<Long> ids = new ArrayList<>();
        courseChapters.forEach(chapter->{
            Long id = chapter.getId();
            ids.add(id);
        });*/
        courseChapters.forEach(chapter->{
            JSONResult jsonResult = mediaSearchFeignClient.searchMediaFiles(chapter.getId());
            if(jsonResult.isSuccess() && jsonResult.getData() != null){
                String s = jsonResult.getData().toString();
                List<MediaFile> mediaFiles = JSONObject.parseArray(s, MediaFile.class);
                chapter.getMediaFiles().addAll(mediaFiles);
            }
        });
        vo.setCourse(course);
        vo.setCourseChapters(courseChapters);
        vo.setCourseDetail(courseDetail);
        vo.setCourseSummary(courseSummary);
        vo.setCourseMarket(courseMarket);
        vo.setTeachers(teachers);





       /* private CourseMarket courseMarket;
        private Course course;
        private List<CourseChapter> courseChapters;
        private List<Teacher> teachers;
        private CourseSummary courseSummary;
        private CourseDetail courseDetail;*/


        return vo;
    }

    @Override
    public CourserOrderVo courserOrderVo(String courseIds) {
        List<Long> Ids = StrUtils.splitStr2LongArr(courseIds);
        Set<Long> collect = Ids.stream().collect(Collectors.toSet());
        //判断业务
        boolean b = Ids.size() == collect.size();
        AssertUtil.isTrue(b,"你在搞事？");
        List<CourseItemVo> courseInfos = new ArrayList<>();
        BigDecimal totalAmount = new BigDecimal(0);
        for (Long id : collect) {
            Course course = selectById(id);
            AssertUtil.isNotNull(course,"请求非法");
            //判断课程是否上线
            boolean b1 = course.getStatus() == Course.STATE_NOLINE;
            AssertUtil.isTrue(b1,"请求非法");
            CourseMarket courseMarket = courseMarketService.selectById(id);
            AssertUtil.isNotNull(courseMarket,"请求非法！");
            CourseItemVo courseItemVo = new CourseItemVo(course,courseMarket);
            courseInfos.add(courseItemVo);
            totalAmount = totalAmount.add(courseMarket.getPrice());
        }


        return new CourserOrderVo(courseInfos,totalAmount);
    }

    @Override
    public void offLineCourse(Long courseId) {
        Course course = selectById(courseId);
        //判断是否为null
        AssertUtil.isNotNull(course,"课程不存在");
        //判断状态是否已经上架
        boolean on =  course.getStatus() == Course.STATE_NOLINE;//1
        AssertUtil.isTrue(on,"课程状态不对");
        course.setStatus(Course.STATE_OFFLINE);
        boolean b = updateById(course);
        AssertUtil.isTrue(b,"课程发布失败");

    }

    private Course selectByName(String name) {
        EntityWrapper<Course> wrapper = new EntityWrapper<>();
        wrapper.eq("name",name);
        return selectOne(wrapper);
    }
}
